<?php

namespace app\server;

use app\server\ToolServer;
use think\facade\Db;

class ChartServer
{
    /**
     * 首页数据看板
     */
    public function homeTotal($project = '')
    {
        $key = 'homePortals_' . $project;
        $mapProject = !empty($project) ? ['project', '=', $project] : [];
        $total = cache($key);
        if (!empty($total)) {
//            return $total;
        }
        $ToolServer = new ToolServer();
        $todayMap = $ToolServer->getTodayMap();
        $total['app_num'] = getCount('app_seting', []); // 应用数量
        $callMap[] = ['status', '=', 1];
        $vistMap = $callMap = [$todayMap];
        if (!empty($mapProject)) {
            $vistMap[] = $mapProject;
            $callMap[] = $mapProject;
        }
        $activeRow = Db::table(getMonthTable('app_active_logs'))->field('count(distinct(log_id)) as num')->where($vistMap)->find();
        $h5Row = Db::table(getMonthTable('app_ip_logs'))->field('count(distinct(http_referer)) as num')->where($vistMap)->find();
        // 访客日志
        $vist = [
            'h5Num' => $h5Row['num'] ?? 0,
            'activeNum' => $activeRow['num'] ?? 0,
            'callNum' => getCount(getMonthTable('app_call'), $callMap)
        ];
        $total['vist'] = $vist;

        // 投放数据
        $spreadMap = [['report_date', '=', date('Ymd', time() - 3600 * 24)]];
        if (!empty($mapProject)) {
            $spreadMap[] = $mapProject;
        }
        $spreadRow = Db::table('app_spread')->field('sum(click_num) as click_num,sum(show_num) as show_num,sum(used_cost) as used_cost')->where($spreadMap)->find();
        $spread = [
            'show_num' => $spreadRow['show_num'] ?? 0,
            'click_num' => $spreadRow['click_num'] ?? 0,
            'rate' => $spreadRow['show_num'] == 0 ? '0%' : sprintf('%01.2f', ($spreadRow['click_num'] / $spreadRow['show_num']) * 100) . "%",
            'used_cost' => $spreadRow['used_cost']
        ];
        $total['spread'] = $spread;
        //变现数据
        $spreadMap[] = ['overall_report', '=', 1];
        $monetizeRow = Db::table('app_monetize')->field('sum(click_num) as click_num,sum(show_num) as show_num,sum(income) as income')->where($spreadMap)->find();
        $monetize = [
            'show_num' => $monetizeRow['show_num'] ?? 0,
            'click_num' => $monetizeRow['click_num'] ?? 0,
            'rate' => $monetizeRow['show_num'] == 0 ? '0%' : sprintf('%01.2f', ($monetizeRow['click_num'] / $monetizeRow['show_num']) * 100) . "%",
            'income' => $monetizeRow['income']
        ];
        $total['monetize'] = $monetize;
        cache($key, $total, 60);
        return $total;
    }

    /**
     * 获取近十日日期
     */
    public function portalDays($daysNum = 10): array
    {
        $days = [];
        for ($i = 0; $i < $daysNum; $i++) {
            $days[] = date('Y-m-d', time() - 3600 * 24 * $i);
        }
        return array_reverse($days);
    }

    /**
     * 最近十天访客数据
     * @return mixed|object|\think\App
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTenDaysVist($project = '')
    {

        $key = 'vistLinesData_' . $project;
//        $vist = cache($key);
//        if (!empty($vistData)) {
//            return $vist;
//        }
        $mapProject = !empty($project) ? ['project', '=', $project] : [];
        $daysNum = 9;
        $tenDays = $this->portalDays();
        $now = time();
        $todayTotal = $this->homeTotal($project);

        // h5阅读数
        $mapDate = [['create_time', 'between', [date('Ymd', $now - 3600 * 24 * $daysNum), date('Ymd', $now - 3600 * 24)]]];
        if (!empty($mapProject)) {
            $mapDate[] = $mapProject;
        }
        $h5NumList = Db::table(getMonthTable('app_ip_logs'))->field('create_time,count(id) as num')->where($mapDate)->group('create_time')->order('create_time asc')->select()->toArray();
        $h5DateList = ToolServer::arrayKeyList($h5NumList, 'create_time');
        $h5Data = [];
        foreach ($tenDays as $value) {
            $h5Data[] = $h5DateList[str_replace('-', '', $value)]['num'] ?? 0;
        }
        $h5Data[9] = $todayTotal['vist']['h5Num'];
        $vist[] = [
            'name' => 'h5访客数',
            'type' => 'line',
            'smooth' => true,
            'data' => $h5Data
        ];

        //激活数量
        $mapDate = [['ymd', 'between', [date('Ymd', $now - 3600 * 24 * $daysNum), date('Ymd', $now - 3600 * 24)]]];
        if (!empty($mapProject)) {
            $mapDate[] = $mapProject;
        }
        $activeNumList = Db::table(getMonthTable('app_active_logs'))->field('ymd,count(distinct(log_id)) as num')->where($mapDate)->group('ymd')->order('ymd asc')->select()->toArray();
        $activeDateList = ToolServer::arrayKeyList($activeNumList, 'ymd');
        $activeData = [];
        foreach ($tenDays as $value) {
            $activeData[] = $activeDateList[str_replace('-', '', $value)]['num'] ?? 0;
        }
        $activeData[9] = $todayTotal['vist']['activeNum'];
        $vist[] = [
            'name' => '激活人数',
            'type' => 'line',
            'smooth' => true,
            'data' => $activeData
        ];

        //回传数量
        $mapDate = [['ymd', 'between', [date('Ymd', $now - 3600 * 24 * $daysNum), date('Ymd', $now - 3600 * 24)]]];
        if (!empty($mapProject)) {
            $mapDate[] = $mapProject;
        }
        $callNumList = Db::table(getMonthTable('app_call'))->field('ymd,count(id) as num')->where($mapDate)->group('ymd')->order('ymd asc')->select()->toArray();
        $callDateList = ToolServer::arrayKeyList($callNumList, 'ymd');
        $callData = [];
        foreach ($tenDays as $value) {
            $callData[] = $callDateList[str_replace('-', '', $value)]['num'] ?? 0;
        }
        $callData[9] = $todayTotal['vist']['callNum'];
        $vist[] = [
            'name' => '回传次数',
            'type' => 'line',
            'smooth' => true,
            'data' => $callData
        ];
        cache($key, $vist, 60);
        return $vist;
    }

    /**
     * 访客分布
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function vistArea($project)
    {
        $daysNum = 10;
        $now = time();
        $mapDate = [['create_time', 'between', [date('Ymd', $now - 10 * 3600 * 24 * $daysNum), date('Ymd', $now - 3600 * 24)]]];
        if (!empty($project)) {
            $mapDate[] = ['project', '=', $project];
        }
        $h5NumList = Db::table(getMonthTable('app_ip_logs'))->field('city,count(id) as num')->where($mapDate)->group('city')->order('num desc')->limit(20)->select()->toArray();
        return [
            'city' => array_column($h5NumList, 'city'),
            'num' => array_column($h5NumList, 'num')
        ];
    }

    /**
     * 投放和推广趋势数据
     *
     * @return \array[][]|mixed|object|\think\App
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTenDaysSpread($project = '')
    {

        $key = 'spreadLinesData_' . $project;
        $vist = cache($key);
        if (!empty($vistData)) {
            return $vist;
        }
        $daysNum = 10;
        $tenDays = $this->portalDays();
        $now = time();
        $mapProject = !empty($project) ? ['project', '=', $project] : [];

        // 推广
        $mapDate = [['report_date', 'between', [date('Ymd', $now - 3600 * 24 * $daysNum), date('Ymd', $now - 3600 * 24)]]];
        if (!empty($mapProject)) {
            $mapDate[] = $mapProject;
        }
        $spreadList = Db::table('app_spread')->field('report_date,sum(click_num) as click_num,sum(show_num) as show_num,sum(used_cost) as used_cost')
            ->where($mapDate)
            ->group('report_date')
            ->select()
            ->toArray();
        $spreadDateList = ToolServer::arrayKeyList($spreadList, 'report_date');

        $mapDate[] = ['overall_report', '=', 1];
        $monetizeList = Db::table('app_monetize')
            ->field('report_date,sum(click_num) as click_num,sum(show_num) as show_num,sum(income) as income')
            ->where($mapDate)
            ->group('report_date')
            ->select()
            ->toArray();
        $monetizeDateList = ToolServer::arrayKeyList($monetizeList, 'report_date');

        $spreadShowNum = $spreadClickNum = $monetizeShowNum = $monetizeClickNum = $spreadCost = $monetizeIncome = $income = [];
        foreach ($tenDays as $value) {
            $key = str_replace('-', '', $value);
            $monetizeDateIncome = $monetizeDateList[$key]['income'] ?? 0;
            $spreadDateListUsedCost = $spreadDateList[$key]['used_cost'] ?? 0;

            $spreadShowNum[] = $spreadDateList[$key]['show_num'] ?? 0;
            $spreadClickNum[] = $spreadDateList[$key]['click_num'] ?? 0;
            $spreadCost[] = $spreadDateListUsedCost;

            $monetizeShowNum[] = $monetizeDateList[$key]['show_num'] ?? 0;
            $monetizeClickNum[] = $monetizeDateList[$key]['click_num'] ?? 0;
            $monetizeIncome[] = $monetizeDateIncome;
            $income[] = sprintf('%01.2f', $monetizeDateIncome - $spreadDateListUsedCost);
        }

        $seriesData = [
            'spread' => [
                [
                    'name' => '展示数',
                    'smooth' => true,
                    'type' => 'line',
                    'data' => $spreadShowNum
                ],
                [
                    'name' => '点击数',
                    'type' => 'line',
                    'smooth' => true,
                    'data' => $spreadClickNum
                ]
            ],
            'monetize' => [
                [
                    'name' => '展示数',
                    'type' => 'line',
                    'smooth' => true,
                    'data' => $monetizeShowNum
                ],
                [
                    'name' => '点击数',
                    'type' => 'line',
                    'smooth' => true,
                    'data' => $monetizeClickNum
                ]
            ],

            'income' => [
                [
                    'name' => '推广消耗成本',
                    'type' => 'line',
                    'data' => $spreadCost
                ],
                [
                    'name' => '变现收入',
                    'type' => 'line',
                    'smooth' => true,
                    'data' => $monetizeIncome
                ],
                [
                    'name' => '最终收入',
                    'type' => 'line',
                    'smooth' => true,
                    'data' => $income
                ]
            ]
        ];
        cache($key, $seriesData, 60);
        return $seriesData;

    }
}

?>